﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Media.Animation;
using System.Xml;
using Microsoft.Phone.Controls;

namespace Forismatic
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
            FixHeight();
            Storyboard storyboardFadeOut = new Storyboard();
            storyboardFadeOut.Completed += BackgroundOutCompleted;
            Fade(ContentStackPanel, storyboardFadeOut, false, 0);
        }

        private void ContentPanelTap(object sender, System.Windows.Input.GestureEventArgs e)
        {            
            Storyboard storyboardFadeOut = new Storyboard();
            storyboardFadeOut.Completed += BackgroundOutCompleted;
            Fade(ContentStackPanel, storyboardFadeOut, false, 0);
        }

        private void BackgroundOutCompleted(object sender, EventArgs e)
        {
            UpdateQuote();
        }

        private void UpdateQuote()
        {
            Random random = new Random();
            WebClient webClient = new WebClient();
            Storyboard storyboardFadeIn = new Storyboard();
            webClient.DownloadStringAsync(new Uri("http://api.forismatic.com/api/1.0/?method=getQuote&key=" + random.Next(1000000) +"&format=xml&lang=ru"));
            webClient.DownloadStringCompleted += (s, ev) =>
            {
                if(ev.Error != null)
                {
                    Quote.Text = "Невозможно загрузить цитату.";
                    Author.Text = "Системная ошибка";
                    FixHeight();
                    Fade(ContentStackPanel, storyboardFadeIn, true, 1);
                    return;
                }
                using (XmlReader reader = XmlReader.Create(new StringReader(ev.Result)))
                {
                    reader.ReadToDescendant("quoteText");
                    Quote.Text = reader.ReadElementContentAsString();
                    reader.ReadStartElement();
                    reader.ReadToDescendant("quoteAuthor");
                    Author.Text = reader.Value;
                    if (string.IsNullOrWhiteSpace(Author.Text))
                        Author.Text = "Автор не указан";
                }
                FixHeight();
                Fade(ContentStackPanel, storyboardFadeIn, true, 1);
            };            
        }

        public void Fade(DependencyObject target, Storyboard storyboard, bool isFadeIn, double? maxOpacity)
        {
            Duration duration = new Duration(TimeSpan.FromSeconds(1));
            DoubleAnimation animation = new DoubleAnimation();
            animation.Duration = duration;
            if (isFadeIn)
            {
                animation.From = 0.00;
                animation.To = maxOpacity;
            }
            else
            {
                animation.From = maxOpacity;
                animation.To = 0.00;
            }
            storyboard.Duration = duration;
            storyboard.Children.Add(animation);
            Storyboard.SetTarget(animation, target);
            Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
            storyboard.Begin();
        }

        private void FixHeight()
        {
            if (Quote.Text.ToCharArray().Length / 21 > 3)
                Quote.Margin = new Thickness(15.0, Convert.ToDouble(Quote.Margin.Top - (Quote.Text.ToCharArray().Length / 21 - 3) * 10), 15.0, 0);
        }
    }
}